package com.example.handpose_front.ExtendedPage;

import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;

import com.example.handpose_front.BaseActivity;
import com.example.handpose_front.DictionarySelectPage.DictionarySelectActivity;
import com.example.handpose_front.R;
import com.example.handpose_front.dto.DataResponse;
import com.example.handpose_front.utils.LocalStorage;
import com.example.handpose_front.utils.OKHttpUtil.HttpUrl;
import com.example.handpose_front.utils.OKHttpUtil.OKHttpUtil;
import com.example.handpose_front.utils.OKHttpUtil.ResponseBody;
import com.prolificinteractive.materialcalendarview.CalendarDay;
import com.prolificinteractive.materialcalendarview.CalendarMode;
import com.prolificinteractive.materialcalendarview.MaterialCalendarView;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class LearningTrackActivity extends BaseActivity implements View.OnClickListener{

    // 切换词典按钮
    private Button changeDictionaryBtn;

    private TextView studiedWords_tv;
    private TextView curDictionaryWords_tv;
    private TextView curDictionaryName_tv;
    private TextView continuousSignedDays_tv;

    private String image_name;
    public String userPhone;

    // 响应体
    private DataResponse dataResponse;

    private String curDictionaryId;
    private String curDictionaryName;
    private String curStudiedWords;
    private String curDictionaryWords;

    private Map<String, String> map = new HashMap<>();
    private String signInfo_s;
    private List<Integer> signInfo;
    private String signCount = "0";

    // 我的数据
    private TextView todayWords_tv;
    private TextView totalWords_tv;
    private TextView todayTime_tv;
    private TextView totalTime_tv;

    private String todayWords = LocalStorage.getTodayWords();
    private String totalWords = "0";
    private String todayTime = "0";
    private String totalTime = "0";

    // 日历控件
    private MaterialCalendarView materialCalendarView;

    @RequiresApi(api = Build.VERSION_CODES.S)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_learning_track);
        initView();
        initEvent();
        sendGetWords_TimeRequest();
        initCalendarView();
    }

    private void initView() {
        // 初始化
        changeDictionaryBtn = findViewById(R.id.change_dictionary_btn);
        curDictionaryName_tv = findViewById(R.id.cur_dic_name);
        studiedWords_tv = findViewById(R.id.studied_words);
        curDictionaryWords_tv = findViewById(R.id.cur_dic_words);
        continuousSignedDays_tv = findViewById(R.id.continuous_signed_days_tv);
        todayWords_tv = findViewById(R.id.today_words_tv);
        totalWords_tv = findViewById(R.id.total_words_tv);
        todayTime_tv = findViewById(R.id.today_time_tv);
        totalTime_tv = findViewById(R.id.total_time_tv);
        userPhone = LocalStorage.getCurrentPhone();
        sendGetCurDictionaryRequest(userPhone);
        initImage();
    }

    @RequiresApi(api = Build.VERSION_CODES.S)
    private void initCalendarView() {
        materialCalendarView = (MaterialCalendarView) findViewById(R.id.calenderView); // 实例化
        //编辑日历属性
        materialCalendarView.state().edit()
                .setFirstDayOfWeek(Calendar.MONDAY)   //设置每周开始的第一天
                .setMinimumDate(CalendarDay.from(2000, 1, 1)) // 设置可以显示的最早时间
                .setMaximumDate(CalendarDay.from(2040, 1, 1)) // 设置可以显示的最晚时间
                .setCalendarDisplayMode(CalendarMode.MONTHS)  // 设置显示模式，可以显示月的模式，也可以显示周的模式
                .commit();  // 返回对象并保存
//        materialCalendarView.setAllowClickWhenDisabled(false); // 无效日期不允许点击
        materialCalendarView.setSelectionMode(MaterialCalendarView.SELECTION_MODE_NONE); // 默认单选模式  这里选择多选模式

        map.clear();
        map.put("userPhone", userPhone);

        String response = OKHttpUtil.postSyncRequest(HttpUrl.getBaseUrl(), map, "userStatus", "signinfo");
        dataResponse = ResponseBody.getResponseBody(response);
        if (dataResponse.getCode().equals("200")) {
            // 一个常犯的错误，空值处理逻辑错误，逻辑会直接进入 else 分支，因为 signInfo_s 初始为 null
//            if (signCount != null) {
//                signCount = dataResponse.getData().get("SignCount").toString();
//            } else {
//                signCount = "0";
//            }
//            if (signInfo_s != null) {
//                signInfo_s = dataResponse.getData().get("SignInfo").toString();
//            } else {
//                signInfo_s = "0";
//            }
            // 1. 提取SignCount（处理null）
            signCount = dataResponse.getData().getOrDefault("SignCount", "0").toString();

            // 2. 提取SignInfo（处理null）
            Object signInfoObj = dataResponse.getData().get("SignInfo");
            signInfo_s = (signInfoObj != null) ? signInfoObj.toString() : "[]"; // 默认空数组
            System.out.println("signInfo_s为：");
            System.out.println(signInfo_s);

            // 去除方括号
            String numbersStr = signInfo_s.replaceAll("\\[|\\]", "");
            // 分割字符串并转换为整数
            String[] numbersArr = numbersStr.split(", ");
            signInfo = new ArrayList<>();
            for (String numStr : numbersArr) {
                signInfo.add(Integer.parseInt(numStr));
            }
            System.out.println("signInfo为：");
            System.out.println(signInfo);

        } else {
            // 提示错误信息
            Toast.makeText(this, "操作失败", Toast.LENGTH_SHORT).show();
        }

        //获取当前时间
        LocalDateTime currentDate = LocalDateTime.now();
        Date now = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(now);
        //获取月份
        int currentMonth = calendar.get(Calendar.MONTH);
//        System.out.println("获取月份为！！！" + String.valueOf(currentMonth + 1));

        for (Integer day_i : signInfo) {

            // 设置当前日期为选中状态
            materialCalendarView.setDateSelected(CalendarDay.from(2025, currentMonth, day_i), true);
        }

        // 连续签到天数
        continuousSignedDays_tv.setText("本月已累计签到 " + signCount + " 天");

    }

    private boolean sendGetWords_TimeRequest() {
        map.clear();

        map.put("userPhone", userPhone);
        String response = OKHttpUtil.postSyncRequest(HttpUrl.getBaseUrl(), map, "curDictionary", "get_totalwords");
        dataResponse = ResponseBody.getResponseBody(response);
        if (dataResponse.getCode().equals("200")) {
            totalWords = dataResponse.getData().get("totalWords").toString();
            totalWords_tv.setText(totalWords + " 词");
            todayWords_tv.setText(todayWords + " 词");
            return true;
        } else {
            // 提示错误信息
            Toast.makeText(this, "操作失败", Toast.LENGTH_SHORT).show();
            return false;
        }
    }

    private void initEvent() {
        // 设置点击事件
        changeDictionaryBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == changeDictionaryBtn.getId()){
            Intent intent = new Intent();
            intent.setClass(this, DictionarySelectActivity.class);
            startActivity(intent);
        }
    }

    public boolean sendGetCurDictionaryRequest(String userPhone) {
        map.clear();

        map.put("userPhone", userPhone);
        String response = OKHttpUtil.postSyncRequest(HttpUrl.getBaseUrl(), map, "curDictionary", "get_cur");
        dataResponse = ResponseBody.getResponseBody(response);
        if (dataResponse.getCode().equals("200")) {
            curDictionaryId = dataResponse.getData().get("curDictionaryId").toString();
            curStudiedWords = dataResponse.getData().get("curStudiedWords").toString();
            sendGetHandDictionaryRequest(curDictionaryId);
            studiedWords_tv.setText("已学习" + curStudiedWords);
            return true;
        } else {
            // 提示错误信息
            Toast.makeText(this, "操作失败", Toast.LENGTH_SHORT).show();
            return false;
        }
    }

    public boolean sendGetHandDictionaryRequest(String handDictionaryId) {
        map.clear();

        map.put("handDictionaryId", handDictionaryId);
        String response = OKHttpUtil.postSyncRequest(HttpUrl.getBaseUrl(), map, "handDictionary", "get_dic");
        dataResponse = ResponseBody.getResponseBody(response);
        if (dataResponse.getCode().equals("200")) {
            curDictionaryName = dataResponse.getData().get("handDictionaryName").toString();
            curDictionaryWords = dataResponse.getData().get("handDictionaryWords").toString();
            curDictionaryName_tv.setText(curDictionaryName);
            curDictionaryWords_tv.setText("总词数" + curDictionaryWords);
            // 用户登录成功
            return true;
        } else {
            // 提示错误信息
            Toast.makeText(this, "操作失败", Toast.LENGTH_SHORT).show();
            return false;
        }
    }

    private void initImage() {
        ImageView imageView = findViewById(R.id.dic_cover);
        ApplicationInfo appInfo = getApplicationInfo();
        if (curDictionaryId.equals("1")) {
            image_name = "chinese_dictionary";
        }
        if (curDictionaryId.equals("2")) {
            image_name = "usa_dictionary";
        }
        if (curDictionaryId.equals("3")) {
            image_name = "french_dictionary";
        }
        int resID = getResources().getIdentifier(image_name, "drawable", appInfo.packageName);
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), resID);
        imageView.setImageBitmap(bitmap);
    }

}